﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using KP_CommonLibrary.KP_Interface;
using KP_CommonLibrary.KP_CommonControls;
using DevComponents.DotNetBar.SuperGrid;
using KP_CommonLibrary.KP_Function;

namespace KP_CommonLibrary.KP_CoreUI
{
    public partial class KP_UCListItem : KP_CommonLibrary.KP_CommonControls.KP_UserControl, ISearchable
    {
        private bool SearchMode = false;
        [Browsable(false)]
        public KP_EditListItem Editor { get; set; }
        [Browsable(false)]
        public KP_SearchForm SearchForm { get; set; }
        [Browsable(false)]
        public KP_Business.KP_BLListBase Business { get; set; }
        public string SelectFields { get; set; }
        public KP_UCListItem()
        {
            InitializeComponent();
            Disposed += new EventHandler(KP_UCListItem_Disposed);
            if (!DesignMode)
                Initialize();
        }


        void KP_UCListItem_Disposed(object sender, EventArgs e)
        {
            
            ReleaseResource();
        }
        public DataTable MainDataSource
        {
            get
            {
                return MainBindingSource.DataSource as DataTable;
            }
            set
            {
                MainBindingSource.DataSource = value;
            }
        }
        public DataRow CurrentRow
        {
            get
            {
                if (MainGrid.ActiveRow != null)
                {
                    GridRow currentRow = MainGrid.PrimaryGrid.Rows[MainGrid.ActiveRow.RowIndex] as GridRow;
                    return (currentRow.DataItem as DataRowView).Row;
                }
                return null;
            }
        }
        protected virtual void Initialize()
        {
        }
        public override bool DispatchCmdKey(ref Message msg, Keys keyData)
        {
            return kpucNavVoucher1.DispatchCmdKey(ref msg, keyData);
        }
        public virtual void ReleaseResource()
        {
            if (Editor != null)
                Editor.Dispose();
            if (SearchForm != null)
                SearchForm.Dispose();
        }
        protected virtual void ChangeCodeClick()
        {
        }
        protected virtual void ExportClick()
        {
            using (SaveFileDialog sfdl = new SaveFileDialog())
            {
                sfdl.Filter = "Excel(*.xls)|*.xls";
                sfdl.ShowDialog();
                if (sfdl.FileName.Length > 0)
                {
                    ExportExcel.ExportToExcel(MainGrid, sfdl.FileName, "");
                    //ExportExcel.ExportToExcel(MainDataSource, sfdl.FileName, "");
                }
            }
        }

        protected virtual void DoSearch()
        {
            try
            {
                if (SearchForm.ShowDialog() == DialogResult.OK)
                {
                    if (SearchForm.ApplyMode == ApplyMode.String)
                        ApplySearchCondition(SearchForm.SearchCondition);
                    else if (SearchForm.ApplyMode == ApplyMode.Dictionary)
                        ApplySearchCondition(SearchForm.ParameterCondition);
                    else
                        ApplySearchCondition(SearchForm.Data);

                }
            }
            catch (Exception ex)
            {
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }
        protected virtual void ApplySearchCondition(string searchCondition)
        {
            if (Business != null)
            {
                MainDataSource = Business.Select(searchCondition, SelectFields);
            }
        }
        protected virtual void ApplySearchCondition(Dictionary<string, object> param)
        {
        }
        protected virtual void ApplySearchCondition(object data)
        {
            MainDataSource = (DataTable)data;
        }
        public virtual string GetConfirmDeleteMessage()
        {
            return "Bạn có chắc muốn xóa bản ghi này?";
        }
        private void kpucNavVoucher1_KPCloseButtonClick(object sender, EventArgs e)
        {
            Close();
            Control temp = Parent;
            int parentType = 0;
            while (true)
            {
                if (temp is SuperTabControlPanel)
                {
                    parentType = 1;

                }
                //if (temp is SuperTabItem)
                //{
                //    parentType = 2;
                //}
                if (temp is OfficeForm)
                {
                    parentType = 4;
                }
                if (temp is Form)
                {
                    parentType = 3;
                }

                if (parentType != 0)
                    break;
                else
                    if (temp == null)
                        break;
                    else
                        temp = temp.Parent;
            }

            switch (parentType)
            {
                case 1:
                    SuperTabControlPanel supertabpanel = temp as SuperTabControlPanel;
                    supertabpanel.TabItem.Close();
                    break;
                case 2:
                    //  SuperTabItem tab = temp as SuperTabItem;
                    //tab.Close();
                    break;
                case 3:
                    Form frm = temp as Form;
                    if (frm.Modal)
                        frm.DialogResult = DialogResult.Cancel;
                    else
                        frm.Close();
                    break;
                case 4:
                    OfficeForm barForm = temp as OfficeForm;
                    if (barForm.Modal)
                    {
                        barForm.DialogResult = DialogResult.Cancel;
                    }
                    else
                        barForm.Close();
                    break;
                default:
                    Parent.Controls.Remove(this);
                    this.Dispose();
                    break;
            }
            //DevComponents.DotNetBar.SuperTabItem newtab = sTabMain.CreateTab("Danh sách kho");
            //DevComponents.DotNetBar.SuperTabControlPanel panel = (DevComponents.DotNetBar.SuperTabControlPanel)newtab.AttachedControl;
            //panel.Controls.Add(abc);
        }

        protected virtual void CreateEditor()
        {

        }
        #region ISearchable Members

        public object SelectedObject
        {
            get
            {

                return CurrentRow;

            }
        }

        public DialogResult ShowSearchUI()
        {
            SearchMode = true;
            KP_FormBase01 frmBase = new KP_FormBase01();
            frmBase.Controls.Add(this);
            DialogResult result = frmBase.ShowDialog();
            frmBase.Controls.Remove(this);
            frmBase.Dispose();
            return result;
        }

        #endregion

        private void MainGrid_RowDoubleClick(object sender, DevComponents.DotNetBar.SuperGrid.GridRowDoubleClickEventArgs e)
        {
            //e.GridRow.SetActive(true);
            if (SearchMode)
            {

                FindForm().DialogResult = DialogResult.OK;
            }
            else
            {
                kpucNavVoucher1_KPEditButtonClick(sender, new EventArgs());
            }
        }
        protected virtual void EditClick()
        {
            try
            {
                CreateEditor();
                CurrencyManager cm = (CurrencyManager)BindingContext[MainBindingSource];
                Editor.Edit(cm);
                DialogResult result = Editor.ShowDialog();
                MainDataSource.RejectChanges();

            }
            catch (Exception ex)
            {
                KPMessageBox.Show("Cập nhật: " + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }
        private void kpucNavVoucher1_KPEditButtonClick(object sender, EventArgs e)
        {
            EditClick();
        }
        protected virtual void AddClick()
        {
            try
            {
                CreateEditor();
                CurrencyManager cm = (CurrencyManager)BindingContext[MainBindingSource];
                Editor.AddNew(cm);
                DialogResult result = Editor.ShowDialog();
                MainDataSource.RejectChanges();
                //MainGrid.PrimaryGrid.FlushActiveRow();
                //MainGrid.PrimaryGrid.FlushSelected();
                //MainGrid.PrimaryGrid.InvalidateRender();
                
                MainBindingSource.ResetBindings(true);


            }
            catch (Exception ex)
            {
                KPMessageBox.Show("Thêm mới: " + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }
        private void kpucNavVoucher1_KPAddButtonClick(object sender, EventArgs e)
        {
            AddClick();
        }

        protected virtual void DeleteClick()
        {
            try
            {
                this.SuspendLayout();
                if (Business != null && CurrentRow != null)
                {
                    if (KPMessageBox.Show(GetConfirmDeleteMessage(), KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.YesNo, KPMessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Business.Delete(CurrentRow);
                        CurrentRow.Delete();
                        MainDataSource.AcceptChanges();
                        MainGrid.Refresh();
                    }
                }
                else
                    throw new Exception("Không có lớp nghiệp vụ hoặc chưa chọn dữ liệu");
            }
            catch (Exception ex)
            {
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                ResumeLayout();
            }
        }
        private void kpucNavVoucher1_KPDeleteButtonClick(object sender, EventArgs e)
        {
            DeleteClick();
        }

        private void kpucNavVoucher1_KPExportButtonClick(object sender, EventArgs e)
        {
            ExportClick();
        }

        private void MainGrid_GridPreviewKeyDown(object sender, GridPreviewKeyDownEventArgs e)
        {
            bool flag = CanHandleGridPreviewKey();
            if (flag)
            {
                Message m = new Message();
                e.Handled = kpucNavVoucher1.DispatchCmdKey(ref m, e.KeyData);
            }


        }
        private bool CanHandleGridPreviewKey()
        {
            return (MainGrid.ActiveFilterPanel == null && MainGrid.ActiveEditor == null && MainGrid.ActiveCell == null);
        }

        private void kpucNavVoucher1_KPFindButtonClick(object sender, EventArgs e)
        {
            DoSearch();
        }

        private void kpucNavVoucher1_KPChangeCodeButtonClick(object sender, EventArgs e)
        {
            ChangeCodeClick();
        }

        private void KP_UCListItem_Load(object sender, EventArgs e)
        {
            MainGrid.DefaultVisualStyles.CellStyles.Default.Font = KP_UIConfig.EditControlFont;
            MainGrid.DefaultVisualStyles.ColumnHeaderStyles.Default.Font = KP_UIConfig.GridHeaderFont;
            MainGrid.DefaultVisualStyles.ColumnHeaderStyles.Default.Alignment = DevComponents.DotNetBar.SuperGrid.Style.Alignment.MiddleLeft;
        }
    }
}
